package com.ifcar.app.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.ifcar.app.activity.MyApplication;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.activity.R;


public class CollectPicturesAdapter extends BaseAdapter {

	private List<Map<String, Object>> mList;
	private Context mContext;
	private boolean mIsSee;
	private SQLiteDatabase db;
	private MyApplication app;
	private BaseImageDownloader mImageDownloader = null;
	private LayoutInflater mInflater; 
	private CheckBox mGlobal;
	
	private boolean allCheckStatus;
	private int mSelectNum;
	private int mImageWidth;
    private int mImageHeight;
	/**
	 * 收藏适配器
	 * 
	 * @param context
	 * @param list
	 * @param gridView 
	 * @param isSee
	 */
	public CollectPicturesAdapter(Context context, List<Map<String, Object>> list, boolean isSee,CheckBox global) {
		mContext = context;
		mList = list;
		mIsSee = isSee;
		mGlobal = global;
		app = (MyApplication)mContext.getApplicationContext();
		db = app.getSQLiteDatabase();	
		mImageDownloader =  new BaseImageDownloader(mContext,null);
		mImageDownloader.setThread(Thread.currentThread());
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		float density = context.getResources().getDisplayMetrics().density;
        mImageWidth = (int) (140 * density);
        mImageHeight = (int) (147 * density);
	}

	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	
	private class GridHolder {
        ImageView appImage;  
        TextView appName;  
        CheckBox appcb;
    }
   
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		
		GridHolder holder;  
		if (convertView == null) {
			holder = new GridHolder();  
			
			convertView = mInflater.inflate(R.layout.collect_item_photo, null);    
			holder.appImage = (ImageView)convertView.findViewById(R.id.photosetitemimage);  
	        holder.appName = (TextView)convertView.findViewById(R.id.photosetitemtext);  
	        holder.appcb = (CheckBox)convertView.findViewById(R.id.collect_item_checkbox);  
            
            convertView.setTag(holder);  
		}else{
			 holder = (GridHolder) convertView.getTag();   
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(mList.size()>0)
			map = mList.get(position);

		Object o = map.get(NewsSQLiteOpenHelper.COLLECT_TITLE);
		String sTitle = null==o?"":o.toString();	
		o = map.get(NewsSQLiteOpenHelper.COLLECT_AUTOID);
		final String deleteId = null==o?"":o.toString();
		
		String imageUrl = StringUtil.GetString(map.get(NewsSQLiteOpenHelper.COLLECT_PATH));
		
		
		int width = mImageWidth - holder.appImage.getPaddingLeft()
        - holder.appImage.getPaddingRight();
		int height = mImageHeight - holder.appImage.getPaddingTop()
        - holder.appImage.getPaddingBottom();
		System.out.println("imageUrl:"+imageUrl);
		mImageDownloader.downloadPictures(imageUrl, holder.appImage, width,height, "Y", null, "picture");

		holder.appName.setText(sTitle);
		holder.appcb.setTag(deleteId);
		if (mIsSee) {
			holder.appcb.setVisibility(View.INVISIBLE);
		} else {
			holder.appcb.setVisibility(View.VISIBLE);		
			
			if(allCheckStatus) holder.appcb.setChecked(true);
			else {
				
				String s = "select * from " + NewsSQLiteOpenHelper.COLLECT_TABLE + 
				" where " + NewsSQLiteOpenHelper.COLLECT_AUTOID + "='" + deleteId + "'";
				Cursor c = db.rawQuery(s, new String[]{});
				if(c != null && c.getCount() > 0 && c.moveToFirst() 
						&& c.getString(c.getColumnIndex(NewsSQLiteOpenHelper.COLLECT_ISCHECKED)) != null
						&& c.getString(c.getColumnIndex(NewsSQLiteOpenHelper.COLLECT_ISCHECKED)).equals("1")) {
					holder.appcb.setChecked(true);
				} else {
					holder.appcb.setChecked(false);
				}
				if(c!=null)	 c.close();
			
			}
			
			holder.appcb.setOnClickListener(new CheckBox.OnClickListener() {
				@Override
				public void onClick(View v) {
					
					CheckBox b = (CheckBox) v;
					
					ContentValues initialValues = new ContentValues();
					if(b.isChecked()) {
						initialValues.put(NewsSQLiteOpenHelper.COLLECT_ISCHECKED, "1");
						mSelectNum ++;
					} else {
						initialValues.put(NewsSQLiteOpenHelper.COLLECT_ISCHECKED, "0");
						mSelectNum --;
					}
					db.update(NewsSQLiteOpenHelper.COLLECT_TABLE, initialValues, "auto_id=?", new String[]{deleteId});
					
					if(mSelectNum == getCount()){
					    mGlobal.setChecked(true);
					    allCheckStatus = true;
					}else{
					    mGlobal.setChecked(false);
					    allCheckStatus = false;
					}
					
				}
			});			
		}
		
		return convertView;
	}
	
	public void setCheckOrNoAllBox(boolean isChecked) {
		allCheckStatus = isChecked;
		if(isChecked){
			mSelectNum = getCount();
		}else{
			mSelectNum = 0;
		}
	}
	
	public int getSelectNums() {
		return mSelectNum;
	}
}
